<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Admin\Models\Activity;
use App\Services\Common;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Widgets;
use Encore\Admin\Widgets\InfoBox;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Ixudra\Curl\Facades\Curl;
use DB;
use SimpleSoftwareIO\QrCode\Facades\QrCode;



class ActivityController extends Controller
{
	use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('活动')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('产品')
            ->description('详细')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('产品')
            ->description('编辑')
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('产品')
            ->description('新增')
            ->body($this->form());
    }

//  public function update(Request $request, $id)
//  {
//
//  }

//  /**
//   * Handle update.
//   *
//   * @param int $id
//   *
//   * @return \Symfony\Component\HttpFoundation\Response
//   */
//  public function update($id, $data = null)
//  {
//
//      return $this->returnMsg(1, $id);
//  }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
    	$sId = Admin::user()->sId;

        $grid = new Grid(new Activity);
        $grid->model()->where('acId', '=', $sId);
        $grid->adId('ID');
        $grid->adTitle('名称');
        $grid->adType("活动类型");
        $grid->adApplyBeginTime('报名开始时间');
        $grid->adApplyEndTime('报名结束时间');
//      $grid->adSiteDescribe('地点');
        $grid->adCurrentPrice('价格');
        $grid->adApplyNum('报名人数');
        $grid->adServicerName('活动联系人');
        $grid->adServicerMobile('服务电话');
        $grid->createTime('创建时间');
        $grid->column('活动微信链接地址')->display(function () use($sId) {
		    return "http://".$_SERVER["HTTP_HOST"]."/activity/activityView?sId=".$sId."&adId=".$this->adId;
		});
		// 添加不存在的字段
		$grid->column('报名')->display(function () {
		    return "<a href='./activity/applyList?adId=".$this->adId."'>详情</a><script> 
        jQuery('.column-adType').each(function(){
        
		    if($(this).text().indexOf('三方活动')>-1){
                $(this).next().next().next().text('');
                $(this).next().next().next().next().text('');
                $(this).next().next().next().next().next().text('');
                $(this).next().next().next().next().next().next().text('');
                $(this).next().next().next().next().next().next().next().text('');
                $(this).next().next().next().next().next().next().next().next().text('');
                $(this).next().next().next().next().next().next().next().next().next().text('');
		    }
		    });</script>";
		});

//		$grid->filter(function($filter){
//
//		    // 去掉默认的id过滤器
//		    $filter->disableIdFilter();
//
//		});

		$grid->actions(function ($actions) {
		    $actions->disableDelete();
//		    $actions->disableEdit();
		    $actions->disableView();
		});

		// 默认展开筛选框
//		$grid->expandFilter();

		// 禁用查询过滤器
		$grid->disableFilter();

		// 禁用行选择checkbox
		$grid->disableRowSelector();

		// 禁用导出
		$grid->disableExport();
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
    	$Product = new Product();
        $show = new Show($Product->findOrFail($id));

        $show->sgId('ID');
        $show->sgName('产品名称');
        $show->sgLogo('产品图片');
        $show->sgDesc('产品描述');
        $show->sgPrice('产品单价');
        $show->field('serviceIds', "服务项目")->as(function ($serviceIds) {
                    return $serviceIds->pluck('name');
                })->label();
        $show->dpId('分销规则');
		$Common = new Common();
		$dpSelect = $Common->getPreceptSelect();
        $show->dpId('分销规则')->using($dpSelect);
        $show->sgNum('库存');
        $show->sgWarningNum('库存警报数量');
        $show->createTime('创建时间');
        $show->updateUser('最后修改人');
        $show->updateTime('最后修改时间');
		$show->sgIsChaffer('议价')->using(['1' => '是','0' => '否'])->value('1');
		$show->panel()
			->tools(function ($tools) {
//				$tools->disableEdit();
//				$tools->disableList();
				$tools->disableDelete();
		});;
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id=false)
    {
        return Admin::Form(Activity::class, function (Form $form) {
            $form->select('adType', '活动类型')->options(array("门店活动"=>"门店活动","三方活动"=>"三方活动"));
			$form->text('adTitle', '活动名称')->rules("required", ['required' => '请填写活动名称']);
			$form->image('adPicUrl', '广告图')->removable()->uniqueName();
			$form->datetime('adApplyBeginTime', '报名开始时间')->format('YYYY-MM-DD HH:mm:ss')->rules("required", ['required' => '请填写报名开始时间']);
			$form->datetime('adApplyEndTime', '结束开始时间')->format('YYYY-MM-DD HH:mm:ss')->rules("required", ['required' => '请填写报名结束时间']);
			$form->text('adSiteDescribe', '活动地点')->rules("required", ['required' => '请填写活动地点']);
            $form->multipleSelect('serviceIds', '服务项目')->options($this->getServiceSelect());
			$form->number('adCurrentPrice', '价格')->default(0);
//			$form->text('adDetails', '活动描述');
			$form->UEditor('adDetails', '活动描述')->options(['initialFrameHeight' => 400]);
			$form->text('adServicerName', '活动联系人')->rules("required", ['required' => '请填写活动联系人']);
			$form->mobile('adServicerMobile', '联系电话')->rules('required|regex:/^[1][0-9]{10}$/', [
        									'required' => '请填写手机号',
        									'regex' => '手机号格式不正确'
        									])
        									->attribute(['style' => 'width: 25%'])
        									->rules("required", ['required' => '请填写联系电话']);

			$form->saved(function (Form $form) {

			    $adId = $form->model()->adId;
				DB::table('activity_definition')->where('adId', $adId)->update(['createUser'=> Admin::user()->name, 'acId' => Admin::user()->sId]);
			});

            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
//			    $tools->disableList();

			    // 去掉`删除`按钮
			    $tools->disableDelete();

			    // 去掉`查看`按钮
			    $tools->disableView();

			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});

			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();

			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();

			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();

			    // 去掉`继续创建`checkbox
//			    $footer->disableCreatingCheck();

			});
        });
    }
    private function getServiceSelect(){
        $infoList = DB::table('reserve_service')->get();
        $selectData = array();
        foreach($infoList as $info){
            $selectData[$info->id] = $info->title;
        }
        return $selectData;
    }
    public function applyList(Request $request, Content $content){

    	$adId = $request->input('adId');

    	$adInfo = DB::table('activity_definition')->where('adId', $adId)->first();

    	$content->title('报名信息');
        $content->description('详情');

        //$this->showFormParameters($content);

        $tab = new Widgets\Tab();

		/////////////////////////////////////////////////////////////////////////////////
		$headers = ['Id', '姓名', '微信昵称', '手机号', '报名时间', '推荐人', '分销盈利', '分享二维码'];

		$sId = Admin::user()->sId;

		$applyList = DB::table('activity_apply')
						->selectRaw('activity_apply.*, member_users.muNickName, mu.muHeadUrl, mu.muNickName AS nickName')
						->leftJoin('member_users', 'activity_apply.aaReferrerId', '=', 'member_users.muCode')
						->leftJoin('member_users AS mu', 'activity_apply.uId', '=', 'mu.muCode')
						->where('activity_apply.acId', $sId)
						->where('activity_apply.adId', $adId)
						->where('aaStats', 1)
						->orderBy('activity_apply.aaId', 'DESC')
						->get();
		$applyList = json_decode(json_encode($applyList), true);
		$rows = array();
		foreach($applyList as $applyInfo){
			$applyTable = array();
			array_push($applyTable, $applyInfo['aaId']);
			array_push($applyTable, $applyInfo['aaName']);
			array_push($applyTable, $applyInfo['nickName']);
			array_push($applyTable, $applyInfo['aaPhone']);
			array_push($applyTable, $applyInfo['createTime']);
			array_push($applyTable, $applyInfo['muNickName']);
			array_push($applyTable, $applyInfo['aaShareMoney']);
			$thisUrl = route('activityView')."?sId=".$sId."&adId=".$adId;
			$shareUrl = $thisUrl."&referrerCode=".$applyInfo['uId'];
//			$shareHtml = '<input id="in_'.$applyInfo['uId'].'" type="hidden" value="'.$shareUrl.'"><div class="shareQr" id="qr_'.$applyInfo['uId'].'" style="width:100px; height:100px;"></div>';
//			array_push($applyTable, $shareUrl);
//			QrCode::format('png')->margin(10)->merge($applyInfo['muHeadUrl'], .2, true)->generate($shareUrl);
			// Download an image from: file http://www.foo.com/bar.png

			$folderPath = "./img/qrcode/{$adId}";
		    $fileName = $applyInfo['aaId'].'.png';

			if (!file_exists($folderPath.'/'.$fileName) && $applyInfo['muHeadUrl']){
				$downloadFile = './download/head/'.$applyInfo['aaId'].'.png';
				if (!file_exists($downloadFile)){
					Curl::to($applyInfo['muHeadUrl'])->withContentType('image/png')->download($downloadFile);
				}

			    $useFile = './download/head/'.$applyInfo['aaId'].'_wb.png';
			    if (!file_exists($useFile)){
			    	$bgFile = './download/head/white.png';
					// open an image file
					$img = Image::make($bgFile);

					// and insert a watermark for example
					$img->insert($downloadFile, 'top-left', 5, 5);
					// finally we save the image as a new file
					$img->save($useFile);
				}

			    if ($applyInfo['muHeadUrl']){
					$base64Img = base64_encode(QrCode::format('png')->margin(0.9)->size(230)->merge($useFile, .2, true)->errorCorrection('H')->generate($shareUrl));
				}else{
					$base64Img = base64_encode(QrCode::format('png')->margin(0.9)->size(230)->generate($shareUrl));
				}

		    	$Common = new Common();
		    	$Common->saveBase64Img($base64Img, $folderPath, $fileName);
		    }

		    $shareHtml = '<img alt="'.$applyInfo['aaName'].'" style="width:50px;height: 50px;" src="'.asset($folderPath.'/'.$fileName).'">';

//			if ($applyInfo['muHeadUrl']){
//				$shareHtml = '<img alt="'.$applyInfo['aaName'].'" style="width:50px;height: 50px;" src="data:image/png;base64, '.base64_encode(QrCode::format('png')->size(230)->margin(0.3)->merge($useFile, .2, true)->errorCorrection('H')->generate($shareUrl)).' ">';
//			}else{
//				$shareHtml = '<img alt="'.$applyInfo['aaName'].'" style="width:50px;height: 50px;" src="data:image/png;base64, '.base64_encode(QrCode::format('png')->size(230)->margin(0.3)->generate($shareUrl)).' ">';
//			}
//			array_push($applyTable, $shareUrl);
			array_push($applyTable, $shareHtml);
//			array_push($applyTable, QrCode::format('png')->size(100)->generate('dfasdfasdfsdf'));
			array_push($rows, $applyTable);
		}

        $table = new Widgets\Table($headers, $rows);
        $tab->add('报名列表', (new Widgets\Box('', $table))->style('danger')->solid());


        Admin::js('https://cdn.bootcss.com/jquery.qrcode/1.0/jquery.qrcode.min.js');
        $script = <<<EOT

for (var i=0;i<$(".shareQr").length;i++){
	var divId = $(".shareQr")[i].id;
   	var inputId = "in_"+divId.substring(3);

    $(".shareQr")[i].qrcode({
//	    render: "table", //table方式
	    width: 100, //宽度
	    height:100, //高度
	    text: $("#"+inputId).value() //任意内容
	});
}
EOT;
//      Admin::script($script);
//return '<div id="qr'.$this->id.'" style="width:100px; height:100px;"></div>';


		/////////////////////////////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////////////////////////////
		$shareList = DB::select('SELECT asv.*, mu1.muNickName AS viewName, mu2.muNickName AS shareName
FROM activity_share_view AS asv
LEFT JOIN member_users AS mu1 ON asv.asvViewUid = mu1.muCode
LEFT JOIN member_users AS mu2 ON asv.asvShareUid = mu2.muCode
WHERE adId = ?
ORDER BY asv.asvId DESC', [$adId]);
		$shareList = json_decode(json_encode($shareList), true);

		$headers = ['Id', '分享人', '浏览人', '首次浏览时间'];

		$rows = array();
		foreach($shareList as $shareInfo){
			$shareTable = array();
			array_push($shareTable, $shareInfo['asvId']);
			array_push($shareTable, $shareInfo['shareName']);
			array_push($shareTable, $shareInfo['viewName']);
			array_push($shareTable, $shareInfo['createTime']);
			array_push($rows, $shareTable);
		}

        $table = new Widgets\Table($headers, $rows);
		$tab->add('有效分享', (new Widgets\Box('', $table))->style('info')->solid());
		/////////////////////////////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////////////////////////////

		$host = config('admin.dataApiHost');
		$url = $host."/distributionBill/getAllList?page=1&perPage=999&dcKey={$sId}&dbObjName=activity&dbObjId=".$adId;

		$billData = Curl::to($url)->get();

		$data = json_decode($billData, true);
		if (!$data){
			echo $data;
			exit;
		}
		if ($data['code'] != 1){
			echo $data['msg'];
			exit;
		}

		$billList = $data['data']['data'];

		$headers = ['Id', '购买人', '推荐人', '返利', '推荐人上级', '上级返利', '分销时间'];

		$rows = array();
		foreach($billList as $billInfo){
			$billTable = array();
			array_push($billTable, $billInfo['dbId']);
//			array_push($billTable, $billInfo['dbObjName']);
//			array_push($billTable, $billInfo['dbSaleNum']);
//			if(($billInfo['dbActualMoney'] && $billInfo['dbActualMoney'] != $billInfo['dbSaleMoney'])){
//				array_push($billTable, $billInfo['dbSaleMoney']."(实际支付：".$billInfo['dbActualMoney'].")");
//			}else{
//				array_push($billTable, $billInfo['dbSaleMoney']);
//			}
			array_push($billTable, $billInfo['userName0']."");
			array_push($billTable, $billInfo['userName1']."");
			array_push($billTable, $billInfo['dbSelfMoney']);
			array_push($billTable, $billInfo['userName2']."");
			array_push($billTable, $billInfo['dbParentMoney']);
//			array_push($billTable, $billInfo['userName3']."");
//			array_push($billTable, $billInfo['dbGrandMoney']);
			array_push($billTable, $billInfo['createTime']);
			array_push($rows, $billTable);
		}


//.box.box-primary {
//	border-top-color: #3c8dbc
//}
//
//.box.box-info {
//	border-top-color: #00c0ef
//}
//
//.box.box-danger {
//	border-top-color: #dd4b39
//}
//
//.box.box-warning {
//	border-top-color: #f39c12
//}
//
//.box.box-success {
//	border-top-color: #00a65a
//}
//
//.box.box-default {
//	border-top-color: #d2d6de
//}

		$table = new Widgets\Table($headers, $rows);
		$tab->add('分销账本', (new Widgets\Box('', $table))->style('warning')->solid());
		/////////////////////////////////////////////////////////////////////////////////
		$Activity = new Activity();
		/////////////////////////////////////////////////////////////////////////////////
		$dayStats = $Activity->getDayStats($adId);
		$dayStats = json_decode(json_encode($dayStats), true);
		$dayStatsHeaders = ['日期', '报名人数', '成功分享次数', '产生分销金额', '收入报名费'];

		$dayStatsRows = array();
		foreach($dayStats as $dayInfo){
			$dayStatsRow = array();
			array_push($dayStatsRow, $dayInfo['day']);
			array_push($dayStatsRow, $dayInfo['dayApplyNum']);
			array_push($dayStatsRow, $dayInfo['dayDisNum']);
			array_push($dayStatsRow, $dayInfo['dayDisMoney']);
			array_push($dayStatsRow, $dayInfo['dayApplyNum']*$adInfo->adCurrentPrice);
			array_push($dayStatsRows, $dayStatsRow);
		}

		$dayStatsTable = new Widgets\Table($dayStatsHeaders, $dayStatsRows);
		$tab->add('每日统计', (new Widgets\Box('每日信息', $dayStatsTable))->style('warning')->solid());
		/////////////////////////////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////////////////////////////
		$shareNumPerson = $Activity->getShareNumPerson($adId);
		$shareMoneyInfo = $Activity->getShareMoneyInfo($adId);
		$haveMoneyNum = $Activity->getHaveMoneyNum($adId);

		$infoHtml = '<div class="row">';
		for ($i=1;$i<5;$i++){
			$infoHtml = $infoHtml.'	<div class="col-md-3 col-sm-6 col-xs-12">';
			if ($i == 1){
				$infoHtml = $infoHtml.'	  <div class="info-box bg-aqua">';
				$infoHtml = $infoHtml.'		<span class="info-box-icon"><i class="fa fa-bookmark-o"></i></span>';
				$infoHtml = $infoHtml.'		<div class="info-box-content">';
				$infoHtml = $infoHtml.'		  <span class="info-box-text">总有效分享数</span>';
				$infoHtml = $infoHtml.'		  <span class="info-box-number">'.$shareNumPerson.'</span>';
				$infoHtml = $infoHtml.'		  <div class="progress">';
				$infoHtml = $infoHtml.'			<div class="progress-bar" style="width: 100%"></div>';
				$infoHtml = $infoHtml.'		  </div>';
				$infoHtml = $infoHtml.'			  <span class="progress-description">';
				$infoHtml = $infoHtml.'				通过分享打开链接人数';
				$infoHtml = $infoHtml.'			  </span>';
			} else if ($i == 2) {
				$infoHtml = $infoHtml.'	  <div class="info-box bg-green">';
				$infoHtml = $infoHtml.'		<span class="info-box-icon"><i class="fa fa-thumbs-o-up"></i></span>';
				$infoHtml = $infoHtml.'		<div class="info-box-content">';
				$infoHtml = $infoHtml.'		  <span class="info-box-text">总分销返利金额</span>';
				$infoHtml = $infoHtml.'		  <span class="info-box-number">'.$shareMoneyInfo->totalShareMoney.'</span>';
				$infoHtml = $infoHtml.'		  <div class="progress">';
				$infoHtml = $infoHtml.'			<div class="progress-bar" style="width: 100%"></div>';
				$infoHtml = $infoHtml.'		  </div>';
				$infoHtml = $infoHtml.'			  <span class="progress-description">';
				$infoHtml = $infoHtml.'			            微信手续费0.6%：'.number_format($shareMoneyInfo->commission, 2).'元';
				$infoHtml = $infoHtml.'			  </span>';
			} else if ($i == 3) {
				$infoHtml = $infoHtml.'	  <div class="info-box bg-yellow">';
				$infoHtml = $infoHtml.'		<span class="info-box-icon"><i class="fa fa-calendar"></i></span>';
				$infoHtml = $infoHtml.'		<div class="info-box-content">';
				$infoHtml = $infoHtml.'		  <span class="info-box-text">总获得返利人数</span>';
				$infoHtml = $infoHtml.'		  <span class="info-box-number">'.$haveMoneyNum.'</span>';
				$infoHtml = $infoHtml.'		  <div class="progress">';
				$infoHtml = $infoHtml.'			<div class="progress-bar" style="width: 100%"></div>';
				$infoHtml = $infoHtml.'		  </div>';
				$infoHtml = $infoHtml.'			  <span class="progress-description">';
				$infoHtml = $infoHtml.'				通过分享获得的佣金人数';
				$infoHtml = $infoHtml.'			  </span>';
			} else if ($i == 4) {

			}

			$infoHtml = $infoHtml.'			</div>';
			$infoHtml = $infoHtml.'		</div>';
			$infoHtml = $infoHtml.'	</div>';
		}
		$infoHtml = $infoHtml.'</div>';
		$tab->add('汇总统计', $infoHtml);
		/////////////////////////////////////////////////////////////////////////////////
        $content->row($tab);
        return $content;
    }

    protected function showFormParameters($content)
    {
        $parameters = request()->except(['_pjax', '_token']);

        if (!empty($parameters)) {

            ob_start();

            dump($parameters);

            $contents = ob_get_contents();

            ob_end_clean();

            $content->row(new Widgets\Box('Form parameters', $contents));
        }
    }


}
